<template>
  <div>
    <PageTemplate>
      <div slot="content">
        <PageEditCollapse :is-search="false" :default-collapse="true">
          <div slot="title" class="page-edit-colllapse-title">
            <div style="width: 200px;">{{$t('cm.baseinfo')}}</div>
          </div>
          <div>
            <!-- 表单 -->
            <el-form
              :model="youth"
              label-position="right"
              label-width="150px"
              class="page-edit-colllapse-form"
              :rules="rules"
              ref="youth"
            >
              <el-row>
                <el-col :span="12">
                  <el-form-item :label="$t('sri.subject_Code')" prop="subjectCode">
                    <el-input v-model="youth.subjectCode"></el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item :label="$t('sri.subject_Name')" prop="subjectName">
                    <el-input v-model="youth.subjectName"></el-input>
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row>
                <el-col :span="12">
                  <el-form-item :label="$t('sri.subject_year')" prop="year">
                    <el-input v-model="youth.year"></el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item :label="$t('sri.subject_User')" prop="subjectUser">
                    <!--<el-input v-model="youth.subjectUser"></el-input>-->
                    <PersonSelect id="subjectUser" :value="youth.subjectUser" v-bind:multiple="false"  ></PersonSelect>
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row>
                <el-col :span="12">
                  <el-form-item label="日期" prop="tempTimes">
                    <el-date-picker
                      style="width: 80%"
                      v-model="youth.tempTimes"
                      type="daterange"
                      range-separator="至"
                      start-placeholder="开始日期"
                      end-placeholder="结束日期">
                    </el-date-picker>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item :label="$t('sri.subject_deptName')" prop="deptName">
                    <el-select v-model="youth.deptName" filterable placeholder="请选择">
                      <el-option
                        v-for="(item, index) in subjectDepts"
                        :key="index"
                        :label="item.dictText"
                        :value="item.dictKey"
                      ></el-option>
                    </el-select>
                  </el-form-item>
                </el-col>
                <!-- <el-col :span="12">
                  <el-form-item :label="$t('sri.subject_startTime')" prop="startTime">
                    <el-date-picker v-model="youth.startTime" type="date" placeholder="选择日期"></el-date-picker>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item :label="$t('sri.subject_endTime')" prop="endTime">
                    <el-date-picker v-model="youth.endTime" type="date" placeholder="选择日期"></el-date-picker>
                  </el-form-item>
                </el-col> -->
              </el-row>
              <el-row>
              </el-row>
              <el-row>
                <el-col :span="20">
                  <el-form-item :label="$t('sri.allowDownloadPerson')">
                    <PersonSelect id="participant" :value="participant" @input="(v) => {participant = v}" v-bind:multiple="true"  ></PersonSelect>
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row>
                <el-col :span="20">
                  <el-form-item :label="$t('sri.youth_acceptance')">
                    <el-input v-model="youth.acceptance"></el-input>
                  </el-form-item>
                </el-col>
              </el-row>
            </el-form>
          </div>
        </PageEditCollapse>
        <PageEditCollapse :is-search="false" :default-collapse="true" v-if="this.isExistNameNumber>-1">
          <div slot="title" class="page-edit-colllapse-title">
            <div style="width: 200px;">成果文件</div>
          </div>
          <div>
            <FileUploadCommon
              @uploadSuccess="uploadSuccess"
              @uploadRemove="uploadRemove"
              :fileList="fileList"
              >
              </FileUploadCommon>
          </div>
        </PageEditCollapse>
        <el-row class="row-empty-10"></el-row>
        <el-row>
          <el-button type="primary" @click="submitForm('youth')">{{$t('cm.commit')}}</el-button>
          <el-button type="primary" @click="toList">{{$t('cm.return')}}</el-button>
        </el-row>
      </div>
    </PageTemplate>
  </div>
</template>

<script>
import { ALERT } from '@/utils/responseHandle'
import * as Constant from '@/utils/constant'
import PageTemplate from '@/components/common/PageTemplate'
import PageEditCollapse from '@/components/common/PageEditCollapse'
import FileUploadCommon from '@/components/common/FileUploadCommon'
import HasBtn from '@/mixins/HasBtn'
import { mapState } from 'vuex'
import { COMMON } from '@/utils/commonUtil'
import api_sri from '@/api/api_sri'
import sys_manage from '@/api/sys_manage'
import PersonSelect from '@/components/asc/PersonSelect'
import {getCurrentUserDetail} from '@/api/api.js'

const vailSubjectUserName=(rule,value,callback)=>{
  if(document.getElementById("subjectUser").value) {
    callback();
  }else{
    callback(new Error("必填项"));
  }
};

export default {
  components: {
    PageTemplate, PageEditCollapse, PersonSelect, FileUploadCommon
  },
  data () {
    return {
      youth: {
        id: null,
        subjectCode: null,
        subjectName: null,
        year: null,
        subjectUser: null,
        startTime: null,
        endTime: null,
        deptId: 11,
        deptName: null,
        acceptance: null,
        tempTimes:null,
        createUserName:null
      },
      youthUsers:[],
      participant:null,
      youthFiles: [],
      isExistName:null,
      isExistNameList:[],
      isExistNameNumber:-1,
      subjectDepts: [],
      rules: {
        subjectCode: [
          { required: true, message: '必填项', trigger: 'blur' }
        ],
        subjectName: [
          { required: true, message: '必填项', trigger: 'blur' }
        ],
        year: [
          { required: true, message: '必填项,且为整数', trigger: 'blur' }
        ],
        subjectUser: [
          { required: true, validator: vailSubjectUserName, trigger: 'blur' }
        ],
        startTime: [
          { required: true, message: '必填项', trigger: 'blur' }
        ],
        tempTimes: [
          { required: true, message: '必选项', trigger: 'blur' }
        ],
        // endTime: [
        //   { required: true, message: '必填项', trigger: 'blur' }
        // ],
        deptName: [
          { required: true, message: '必填项', trigger: 'blur' }
        ]
      },
      fileList: []
    }
  },
  created () {
    this.sysDictLoadByPaging();
    if (this.$router.history.current.params.id !== Constant.NEW_PARAMS) {
      this.sriGainYoungSpecialGet(this.$router.history.current.params.id)
      this.getNowUser()
    }
  },
  methods: {
    getNowUser () {
            let _this = this;
            getCurrentUserDetail({}).then((result) => {
              if (result.status == "200" && result.data.code == "0") {
                this.isExistName =this.participant+","+this.youth.createUserName+","+this.youth.subjectUser
                var temp = this.isExistName.split(",");
                  for (var i=0; i<temp.length; i++) {
                    this.isExistNameList.push(temp[i])
                  }

                  this.isExistNameNumber=this.isExistNameList.indexOf(result.data.data.userName)
                 //console.log("srigaintopic-username",this.isExistNameList);
                  //console.log("srigaintopic-username",this.isExistNameList.indexOf("[P206192]叶亮"));
              } else {
                _this.$alert(result.data.msg, _this.$t('cm.tips'));
              }
            }).catch((err) => {
              _this.$alert(err,_this.$t('cm.tips'));
            });
         },
    sriGainYoungSpecialGet (id) {
      api_sri.sriGainYoungSpecialGet({ id }, result => {
        if (result.code === Constant.RT_SUCCESS) {
          this.youth = {
            ...result.data.youth,
            tempTimes: [result.data.youth.startTime, result.data.youth.endTime]
          }
          this.youthUsers = result.data.youthUsers;
          if (this.youthUsers.length > 0) {
            var temps = [];
            for (var i=0; i<this.youthUsers.length; i++) {
              var temp = "[" + this.youthUsers[i].participantId + "]" + this.youthUsers[i].participantName;
              temps.push(temp);
            }
            this.participant = temps.join(",");
          }
          this.fileList = result.data.youthFiles.map(item => {
            return {
              name: item.fileName,
              url: item.filePath,
              fileId: item.fileId
            }
          })
        } else {
          // _this.$t('cm.tips')
          ALERT.error(result.msg)
        }
      })
    },
    sysDictLoadByPaging () {
      sys_manage.sysDictLoadByPaging({dictGroupKey: 'achievement_profession_dept'}, result => {
        if (result.code === Constant.RT_SUCCESS) {
          this.subjectDepts = result.data
        } else {
          ALERT.error(result.msg)
        }
      })
    },
    submitForm (formName) {
      this.$refs[formName].validate((valid, error) => {
        if (valid) {
          this.youth.subjectUser = document.getElementById("subjectUser").value;
          if (this.youth.tempTimes && this.youth.tempTimes.length === 2) {
            this.youth.startTime = this.youth.tempTimes[0]
            this.youth.endTime = this.youth.tempTimes[1]
          }
          if (this.participant != null) {
            var temp = this.participant.split(",");
            for (var i=0; i<temp.length; i++) {
              var endIndx = temp[i].indexOf("]");
              var id = temp[i].substring(1,endIndx);
              var name = temp[i].substring(endIndx+1);
              var curUsers = {"participantId":id, "participantName":name};
              this.youthUsers.push(curUsers);
            }
          }
          let d = {
            youth: this.youth,
            youthUsers: this.youthUsers
          }
          let youthFiles = this.fileList.map(item => {
            return {
              youthId: this.youth.id,
              fileId: item.fileId,
              fileName: item.name,
              filePath: item.url
            }
          })
          d.youthFiles = youthFiles
          api_sri.sriGainYoungSpecialSave(d, result => {
            if (result.code === Constant.RT_SUCCESS) {
              ALERT.success(result.msg)
              this.toList()
            } else {
              // _this.$t('cm.tips')
              ALERT.error(result.msg)
            }
          })
        } else {
          return false
        }
      })
    },
    toList () {
      COMMON.routerTo(Constant.ROUTE_SRI_GAIN_YOUNGSPECIAL.index, this.$router)
    },
    selectAllowDownloadPerson() {},
    uploadSuccess (res, fileKey) {
      if (res.data && res.data[0]) {
        let file = {name: res.data[0].fileName, url: res.data[0].url, fileId: res.data[0].fileId}
        this.fileList.push(file)
      }
    },
    uploadRemove (fileList, fileKey) {
      let resList = fileList.map(item => {
        return {
          name: item.name,
          url: item.url,
          fileId: item.fileId
        }
      })
      this.fileList = resList
    }
  },
  mounted () {
  },
  computed: {
  }
}
</script>

<style lang="scss">
</style>
